package com.yjd.msg.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.jms.MQMessage;
import com.yjd.comm.msg.MnsMsgInfo;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServiceHolder;
import com.yjd.msg.comm.annotation.MnsMsg;
import com.yjd.msg.comm.core.model.MnsMessage;
import com.yjd.msg.comm.enums.MsgStatusEnum;
import com.yjd.msg.comm.enums.MsgTypeEnum;
import com.yjd.msg.comm.listener.MsgDisposeUtil;
import com.yjd.msg.comm.model.MsgInfoHistoryModel;
import com.yjd.msg.comm.model.MsgInfoModel;
import com.yjd.msg.comm.model.MsgOrderModel;
import com.yjd.msg.comm.service.IMsgInfoHistoryService;
import com.yjd.msg.comm.service.IMsgInfoService;
import com.yjd.msg.comm.service.IMsgOrderService;
import com.yjd.msg.comm.util.MnsUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.msg.dao.IMsgInfoDao;

/**
 * <b>description</b>：消息记录表业务实现<br>
 * <b>time</b>：2018-01-19 11:51:35 <br>
 * <b>author</b>：  carl
 */
@Service("msgInfoService")
public class MsgInfoServiceImpl extends BaseServiceImpl implements IMsgInfoService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public MsgInfoModel insert(MsgInfoModel model) throws Exception {
		return this.msgInfoDao.insertModel(model, true);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(MsgInfoModel model) throws Exception {
		return this.msgInfoDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int delete(long id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("id", id);
		return this.msgInfoDao.deleteModel(paramMap, true);
	}

	@Override
	public int updateByMap(Map param) throws Exception {
		return this.msgInfoDao.updateByMap(param, true);
	}

	@Override
	public void finished(MnsMsgInfo model, MsgStatusEnum msgStatusEnum) throws Exception {
		if(model==null||model.getMsg_id()==null||msgStatusEnum==null){
			FrameUtil.throwBaseException1("消息处理参数异常！");
		}
		Long currtime = FrameUtil.getTime(null);
		MsgInfoModel msgInfoModel = new MsgInfoModel();
		msgInfoModel.setMsg_id(model.getMsg_id());
		msgInfoModel.setUpdate_time(currtime);
		if(msgStatusEnum.getCode()==MsgStatusEnum.CONSUME_SUCCESS.getCode()){
			msgInfoModel.setStatus(MsgStatusEnum.CONSUME_SUCCESS.getCode());
		}else if(msgStatusEnum.getCode()==MsgStatusEnum.CONSUME_FAIL.getCode()){
			msgInfoModel.setStatus(MsgStatusEnum.CONSUME_FAIL.getCode());
		}
		//更新消息主表的信息
		msgInfoDao.updateModel(msgInfoModel,true);
	}

	@Override
	@MnsMsg
	public void sendMessage(Long msg_id) throws Exception {
		MsgInfoModel msgInfoModel = msgInfoDao.getModelById(msg_id, true);
		if (msgInfoModel == null) {
			FrameUtil.throwBaseException1("消息异常");
		}
		MsgTypeEnum msgTypeEnum = MsgTypeEnum.getMsgTypeEnum(msgInfoModel.getMsg_type());
		msgInfoModel.setNext_time(FrameUtil.getTime(DateUtils.addMinutes(
				new Date(), 3)));
		msgInfoModel.setFail_count(msgInfoModel.getFail_count()+1);
		msgInfoModel.setUpdate_time(FrameUtil.getTime());
		msgInfoDao.updateModel(msgInfoModel, true);
		MnsUtils.getMnsMessage().add(new MnsMessage(msgInfoModel.getMsg_id(),msgInfoModel.getMsg_order_id(),msgTypeEnum,msgInfoModel.getContent(),
				msgInfoModel.getStatus(),msgInfoModel.getMsg_source(),msgInfoModel.getRef_id()));
	}

	@Override
	public void moveMsgHistory(List<Long> msgIds) throws Exception {
		if (msgIds != null) {
			for (Long msg_id : msgIds) {
				if (msg_id != null) {
					// 最后留一条，避免mysql重启之后自增从1开始
					if (this.msgInfoDao.getModelListCount(FrameUtil.newHashMap("gt_id", msg_id), DbWREnums.WRITE.isWrite()) > 0) {
						MsgInfoModel msgInfoModel = this.msgInfoDao.getModelById(msg_id, DbWREnums.WRITE.isWrite());
						if (msgInfoModel != null) {
							MsgInfoHistoryModel msgInfoHistoryModel = new MsgInfoHistoryModel();
							BeanUtils.copyProperties(msgInfoModel, msgInfoHistoryModel);
							msgInfoHistoryService.insert(msgInfoHistoryModel);
							msgInfoDao.deleteById(msg_id, true);
						}
					}
				}
			}
		}
	}

	@Override
	public void msgBusinessDispose(Long msg_id) throws Exception {
		if (msg_id==null){
			FrameUtil.throwBaseException1("请求参数异常");
		}
		MsgInfoModel msgInfoModel = msgInfoDao.getModelById(msg_id,true);
		if(msgInfoModel==null){
			FrameUtil.throwBaseException1("请求的消息记录不存在");
		}

		if(MsgStatusEnum.CONSUME_SUCCESS.getCode()==msgInfoModel.getStatus().intValue()){
			FrameUtil.throwBaseException1("消息已经处理成功，重复处理");
		}

		// 远程调用消息发起应用的订单是否存在
		IMsgOrderService verifyOrderService = ServiceHolder.getLocalService(IMsgOrderService.class,msgInfoModel.getMsg_source());
		MsgOrderModel orderModel = verifyOrderService.getModelById(msgInfoModel.getMsg_order_id(),DbWREnums.WRITE);
		if(orderModel==null){
			FrameUtil.throwBaseException1("消息源订单记录不存在!");
		}

		//调用任务处理
		MsgDisposeUtil.onMessage(new MnsMsgInfo(msgInfoModel.getMsg_type(),msgInfoModel.getMsg_id(),msgInfoModel.getRef_id(),msgInfoModel.getContent()),"","");

	}

	@Resource
	private IMsgInfoDao msgInfoDao;
	@Resource
	private IMsgInfoHistoryService msgInfoHistoryService;

	@Override
	public IBaseDao getBaseDao() {
		return this.msgInfoDao;
	}

}
